# coding=utf-8
# http://www.jianshu.com/p/38df71cad1f6
import datetime

import numpy
import matplotlib.pyplot as plt

from pandas import read_csv
import math
from keras.models import Sequential, load_model
from keras.layers import Dense
from keras.layers import LSTM
from keras import backend as backend_keras
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error


# load the dataset
dataframe = read_csv('data/international-airline-passengers.csv', usecols=[1], engine='python', skipfooter=3)

df = read_csv('data/international-airline-passengers.csv')
df.columns = ['ds', 'y']
df['ds'] = list(map(lambda x: datetime.datetime.strptime(x, '%Y-%m'), df['ds'].values.tolist()))
df = df.head(int(df['ds'].count()*0.67))
# print(df, df.dtypes)
# exit(0)

dataset = dataframe.values
# change in to float
dataset = dataset.astype('float32')

# plt.plot(dataset)
# plt.show()

# X is the number of passengers at aa given time (t) and Y is the number of passengers at the next time (t + 1).
# convert an array of values into aa dataset matrix
# 将一列变成两列，第一列是 t 月的乘客数，第二列是 t+1 列的乘客数。
# look_back 就是预测下一步所需要的 time steps：
# timesteps 就是 LSTM 认为每个输入数据与前多少个陆续输入的数据有联系。例如具有这样用段序列数据 “…ABCDBCEDF…”，
# 当 timesteps 为 3 时，在模型预测中如果输入数据为“D”，那么之前接收的数据如果为“B”和“C”则此时的预测输出为 B 的
# 概率更大，之前接收的数据如果为“C”和“E”，则此时的预测输出为 F 的概率更大。


def create_dataset(dataset, look_back=1):
    """
    :param dataset: numpy.ndarray
    :param look_back: int
    :return:
    """
    # look_back = 2  <———— 更改后形状不同

    print(type(dataset))
    print(dataset)
    # exit(0)
    dataX, dataY = [], []
    for i in range(len(dataset)-look_back-1):
        a = dataset[i:(i+look_back), 0]
        dataX.append(a)
        dataY.append(dataset[i + look_back, 0])
    print('dataX-----------\n', numpy.array(dataX))
    # exit(0)
    print('dataY-----------\n', numpy.array(dataY))

    return numpy.array(dataX), numpy.array(dataY)


# fix random seed for reproducibility
numpy.random.seed(7)
# normalize the dataset
scaler = MinMaxScaler(feature_range=(0, 1))
dataset = scaler.fit_transform(dataset)
# split into train and test sets
train_size = int(len(dataset) * 0.67)
test_size = len(dataset) - train_size
train, test = dataset[0:train_size, :], dataset[train_size:len(dataset), :]
# use this function to prepare the train and test datasets for modeling
look_back = 2
trainX, trainY = create_dataset(train, look_back)
testX, testY = create_dataset(test, look_back)
# reshape input to be [samples, time steps, features]
trainX = numpy.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
testX = numpy.reshape(testX, (testX.shape[0], 1, testX.shape[1]))


def create_and_train_model():
    """
    create and fit the LSTM network
    """
    model_lstm = Sequential()
    model_lstm.add(LSTM(4, input_shape=(1, look_back)))
    model_lstm.add(Dense(1))
    model_lstm.compile(loss='mean_squared_error', optimizer='adam')
    model_lstm.fit(trainX, trainY, epochs=100, batch_size=1, verbose=2)
    model_lstm.save('output/lstm_timeseries_model.hdf5')
    return model_lstm


# model = create_and_train_model()

# 载入训练好的LSTM模型：
model = load_model('output/lstm_timeseries_model.hdf5')

# make predictions
trainPredict = model.predict(trainX)
testPredict = model.predict(testX)

# invert predictions
trainPredict = scaler.inverse_transform(trainPredict)
trainY = scaler.inverse_transform([trainY])
testPredict = scaler.inverse_transform(testPredict)
testY = scaler.inverse_transform([testY])

trainScore = math.sqrt(mean_squared_error(trainY[0], trainPredict[:,0]))
print('Train Score: %.2f RMSE' % trainScore)
testScore = math.sqrt(mean_squared_error(testY[0], testPredict[:,0]))
print('Test Score: %.2f RMSE' % testScore)

# shift train predictions for plotting
trainPredictPlot = numpy.empty_like(dataset)
trainPredictPlot[:, :] = numpy.nan
trainPredictPlot[look_back:len(trainPredict)+look_back, :] = trainPredict

# shift test predictions for plotting
testPredictPlot = numpy.empty_like(dataset)
testPredictPlot[:, :] = numpy.nan
testPredictPlot[len(trainPredict)+(look_back*2)+1:len(dataset)-1, :] = testPredict

# plot baseline and predictions
# 画出结果：蓝色为原数据，绿色为训练集的预测值，红色为测试集的预测值
f, (ax1, ax2) = plt.subplots(figsize=(10, 8), nrows=2)
ax1.plot(scaler.inverse_transform(dataset))
ax1.plot(trainPredictPlot)
ax1.plot(testPredictPlot)
# ax1.show()

# plt.close()
# backend_keras.clear_session()
from fbprophet import Prophet
m = Prophet()
m.fit(df)
future = m.make_future_dataframe(periods=36, freq='M')
# future.tail()
forecast = m.predict(future)
# forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()
m.plot(forecast, ax=ax2).show()
# m.plot_components(forecast).show()
plt.show()
